<template>
  <div class="container">
    <van-nav-bar title="京东登录" left-text="返回" left-arrow @click-left="onClickLeft" />
    <van-form validate-first validate-trigger="onChange" colon @submit="onSubmit">
      <!-- name: 输出的values对应的key -->
      <van-field
        v-model="username"
        name="username"
        label="用户名"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        label="密码"
        placeholder="密码"
        :rules="[
          {
            required: true,
            pattern,
            message: '密码格式不正确',
          },
        ]"
      />
      <div style="margin: 16px">
        <van-button round block type="danger" native-type="submit"> 提交 </van-button>
      </div>
    </van-form>
    <van-cell-group inset title="去注册">
      <van-cell title="快速注册" is-link to="/register" />
    </van-cell-group>
    <!-- <router-link to="/register">快速注册</router-link> -->
  </div>
</template>

<script lang="ts" setup>
import { ref, type Ref } from 'vue'
import { login } from '@/api/login'
import { Dialog, Notify } from 'vant'
import { useUserStore } from '@/stores/user'
import { useRouter } from 'vue-router'
const router = useRouter()

const username: Ref<string> = ref('17512345666')
const password: Ref<string> = ref('123abcOK!')
// 正则大全:密码
const pattern =
  /^\S*(?=\S{6,})(?=\S*\d)(?=\S*[A-Z])(?=\S*[a-z])(?=\S*[!@#$%^&*? ])\S*$/

const onSubmit = ({
  username,
  password,
}: {
  username: string
  password: string
}) => {
  login({
    loginname: username,
    password: password,
  })
    .then((res: any) => {
      // res: code: "10010" : 该用户不存在, "10011":"密码错误","200": "登录成功",
      // 200:  data: {token,userid,},
      // 登录接口错误处理, 可以放在api层统一处理
      if (res.code === '10010') {
        Dialog.confirm({
          message: res.message,
          confirmButtonText: '立即注册',
        })
          .then(() => {
            router.push('/register')
          })
          .catch(() => {
            // on cancel
          })
      } else if (res.code === '200') {
        // 登录成功保存用户id
        // this.$store.commit("setUserId", res.data.userid);
        const userStore = useUserStore()
        userStore.setUserId(res.data.userid)
        Notify({
          type: 'success',
          onClose: () => {
            router.go(-1)
          },
          message: res.message,
        })
      }
    })
    .catch((err) => {
      console.error(err)
    })
}
const onClickLeft = () => {
  router.back()
}
</script>

<style lang="scss" scoped>
.van-form {
  padding-top: 25px;
}
</style>
